// 正文样式;
KindEditor.plugin('contexttype', function(K) {
  var self = this, name = 'contexttype';
  self.clickToolbar(name, function() {
    var blocks = self.lang('contexttype.contexttype'),
      // 获取当前选中node;
      // cntNode = self.cmd.sel.focusNode
      startNode = self.cmd.range.startContainer
    // 如果光标不在当前编辑器;
    if (!startNode){
      alert("请选中要修改的段落")
      return
    }
    // 获取起始段落;
    while(true){
      // 收敛条件, 当startNode为p标签, 或者父标签为body;
      if("P" == startNode.nodeName){
        break
      }
      else if("BODY" == startNode.parentNode.nodeName){
        var newEl = document.createElement('P')
        newEl.innerHTML = startNode.innerHTML || startNode.textContent
        startNode.replaceWith(newEl)
        startNode = newEl
        break
      }
      startNode = startNode.parentNode
    }

    endNode = self.cmd.range.endContainer
    // 获取结束段落;
    while(true){
      // 收敛条件, 当endNode为p标签, 或者父标签为body;
      if("P" == endNode.nodeName){
        break
      }
      // 如果endNode父节点不存在, 则说明endNode和startNode是同一个, 而且在上一步递归查找startNode时都已被替换;
      else if (!endNode.parentNode){
        endNode = startNode
        break
      }
      else if("BODY" == endNode.parentNode.nodeName){
        var newEl = document.createElement('P')
        newEl.innerHTML = endNode.innerHTML || endNode.textContent
        endNode.replaceWith(newEl)
        endNode = newEl
        break
      }
      endNode = endNode.parentNode
    }

    // 查看当前选中段落样式;
    if(startNode.nodeName){
      curVal = startNode.getAttribute("class")
    }
    menu = self.createMenu({
      name : 'contexttype',
      width : self.langType == 'en' ? 200 : 150
    });
    for(let key  in blocks){
      let val = blocks[key]
      menu.addItem({
        title : '<span class="' + key + '" style="font-size: 16px" unselectable="on">' + val + '</span>',
        height : 30,
        checked : (curVal === key || curVal === val),
        click : function() {
          var cntNode = startNode
          while(true) {
            // 外层标签, 如果是p, 则直接赋值class样式
            if("P" == cntNode.nodeName){
              if(key == 'none'){
                cntNode.removeAttribute('class')
              }
              else {
                cntNode.setAttribute("class", key);
              }
            }
            // 如果外层不是p标签, 则替换为p标签;
            else {
              var newEl = document.createElement('P')
              if (key != 'none'){
                newEl.setAttribute("class", key)
              }
              // 如果外层没有标签, 则取textContent属性, 或者取innerHtml属性;
              newEl.innerHTML = cntNode.innerHTML || cntNode.textContent
              cntNode.replaceWith(newEl)
            }
            if (cntNode == endNode) {
              break;
            }
            else {
              cntNode = cntNode.nextElementSibling
            }
          }
          self.hideMenu();
        }
      })
    }
  })
})
